package com.haitonghop.controls;

import it.sephiroth.android.library.imagezoom.ImageViewTouch;
import it.sephiroth.android.library.imagezoom.graphics.FastBitmapDrawable;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.RectF;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.androidquery.callback.AjaxStatus;
import com.androidquery.callback.BitmapAjaxCallback;
import com.haitonghop.R;
import com.haitonghop.data.HaiBLMetalData;
import com.haitonghop.utils.AppSettingParams;
import com.haitonghop.utils.GlobalData;
import com.haitonghop.utils.Logger;

public class ImagePagerAdapter extends PagerAdapter implements OnPageChangeListener {

	private IOnFinalPage onFinalPage;
	private IOnComicChanged comicChanged;
	private OnClickListener onClickImageViewSingerTapListener = null;
	private ArrayList<HaiBLMetalData> metalDatas;
	private HaiBLMetalData currentData;
	private int currentViewIndex = -1;
	private LayoutInflater inflater = null;
	private Activity aContext = null;

	public ImagePagerAdapter(Activity aContext) {
		inflater = (LayoutInflater) aContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		this.aContext = aContext;
	}

	public void setMetalData(ArrayList<HaiBLMetalData> inputData) {
		if (inputData != null) {
			if (metalDatas == null) {
				metalDatas = inputData;
			} else {
				final int size = inputData.size();
				for (int i = 0; i < size; i++) {
					metalDatas.add(inputData.get(i));
				}
			}
		}
	}

	public boolean isFinalItem(){
		if(metalDatas != null)
			return currentViewIndex == metalDatas.size() - 1;
		else
			return false;
	}

	public void clearData() {
		this.currentData = null;
		this.currentViewIndex = -1;
		this.metalDatas = null;
	}

	public void setNewData(ArrayList<HaiBLMetalData> metalDatas) {
		this.metalDatas = metalDatas;
	}

	@Override
	public int getCount() {
		if (metalDatas != null)
			return metalDatas.size();
		else
			return 0;
	}

	@Override
	public boolean isViewFromObject(View view, Object object) {
		return view == (object);
	}

	public boolean hasScrollableinImageView() {
		return false;
	}

	public void clearListener() {
		onFinalPage = null;
		comicChanged = null;
		metalDatas = null;
		currentData = null;
		inflater = null;
	}

	View contentImageAdapter;
	public boolean noFit = false;
	@Override
	public Object instantiateItem(final ViewGroup container, int position) {
		if (metalDatas != null && position >= getCount() - 1) {
			Logger.logMe(">>>>>>>>>> Requesting final image......");
			if (onFinalPage != null) {
				onFinalPage.onFinalPage();
				final HaiBLMetalData finalData = (metalDatas.get(getCount() - 1));
				onFinalPage.onFinalItem(finalData);
			}
		}

		final View contentImageAdapter = inflater.inflate(R.layout.image_view_content, container, false);
		final ImageViewTouch imageView = (ImageViewTouch) contentImageAdapter.findViewById(R.id.mainImage);
		final WebView imageViewWebView = (WebView) contentImageAdapter.findViewById(R.id.mainImageWebView);

		imageView.setLayoutImageDone(new IOnLayoutImageDone() {

			@Override
			public void onLayoutDone() {

				RectF bitmapRect = new RectF();
				if (imageView.getDrawable() != null) {
					bitmapRect.right = imageView.getDrawable().getIntrinsicWidth();
					bitmapRect.bottom = imageView.getDrawable().getIntrinsicHeight();

					// Translate and scale the bitmapRect according to the
					// imageview's scale-type, etc.
					Matrix m = imageView.getImageMatrix();
					m.mapRect(bitmapRect);

					// Get the width of the image as shown on the screen:
					float width = bitmapRect.width();
					if (width < AppSettingParams.SCREEN_WIDTH) {
						imageView.fitScreenImage();
					}
				}
			}
		});
		imageView.setVisibility(View.INVISIBLE);
		imageView.setPadding(1, 1, 1, 1);
		imageView.setOnClickImageViewSingerTapListener(onClickImageViewSingerTapListener);

		final RelativeLayout loadingContent = (RelativeLayout) contentImageAdapter.findViewById(R.id.loadingContent);
		loadingContent.setVisibility(View.VISIBLE);

		String urlImage = "";
		if (metalDatas != null) {
			HaiBLMetalData data = (metalDatas.get(position));
			urlImage = data.getImageUrl();
		}
//		String html  = "<div>"+
//								   "<table align=\"center\" valign=\"center\">"+
//									   "<tr><td>"+
//									   "   <img src=\""+urlImage+"\" alt=\"foo\" width=\""+(AppSettingParams.SCREEN_WIDTH - 50)+"px\" />"+
//									   "</td></tr>"+
//								   "</table>"+
//						     "</div>";
//		String mime = "text/html";
//		String encoding = "utf-8";
//
//		imageViewWebView.setPadding(0, 0, 0, 0);
//		imageViewWebView.setInitialScale(100);
//		imageViewWebView.getSettings().setJavaScriptEnabled(true);
//		imageViewWebView.loadDataWithBaseURL(null, html, mime, encoding, null);
//
//		imageViewWebView.setWebViewClient(new WebViewClient(){
//
//			public void onPageFinished(WebView view, String url) {
//				Log.i("LOADED", ">>>>>DONE");
//				imageViewWebView.setVisibility(View.VISIBLE);
//				if (loadingContent != null) {
//					loadingContent.setVisibility(View.GONE);
//				}
//			};
//		});

		GlobalData.mAQ.id(imageView).image(urlImage, false, true, 400, 0, new BitmapAjaxCallback() {
			@Override
			public void callback(String url, ImageView imageview, final Bitmap bm, AjaxStatus status) {
				if(bm == null){
					Log.d("NULLLLLLL", "Image u load has null");
				}
				if (aContext != null) {
					aContext.runOnUiThread(new Runnable() {

						@Override
						public void run() {
							if (bm != null) {
								imageView.setImageBitmap(bm);
								imageView.setVisibility(View.VISIBLE);
								if (loadingContent != null) {
									loadingContent.setVisibility(View.GONE);
								}
							}
						}
					});
				} else {
					if (bm != null) {
						imageView.setImageBitmap(bm);
						imageView.setVisibility(View.VISIBLE);
						if (loadingContent != null) {
							loadingContent.setVisibility(View.GONE);
						}
					}
				}

			}
		});

		((ViewPager) container).addView(contentImageAdapter, 0);
		return contentImageAdapter;
	}

	@Override
	public void destroyItem(ViewGroup container, int position, Object object) {
		try {
			if (object != null) {
				final ImageViewTouch imageView = (ImageViewTouch) ((View) object).findViewById(R.id.mainImage);
				if (imageView != null && imageView.getDrawable() != null && imageView.getDrawable() instanceof FastBitmapDrawable) {
					Bitmap bitmap = ((FastBitmapDrawable) imageView.getDrawable()).getBitmap();
					if (bitmap != null) {
						bitmap.recycle();
						bitmap = null;
						System.gc();
					}
				}
				((ViewPager) container).removeView((View) object);
			}
		} catch (NullPointerException e) {

		}
	}

	public void setOnFinalPage(IOnFinalPage onFinalPage) {
		this.onFinalPage = onFinalPage;
	}

	@Override
	public void onPageScrollStateChanged(int arg0) {

	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {

	}

	@Override
	public void onPageSelected(int index) {
		this.currentViewIndex = index;
		if (metalDatas != null && index > -1 && index < getCount()) {
			setCurrentData((metalDatas.get(index)));
			if (comicChanged != null) {
				comicChanged.commicChanged(getCurrentData());
			}
		}
	}

	public HaiBLMetalData getCurrentData() {
		return currentData;
	}

	public void setCurrentData(HaiBLMetalData currentData) {
		this.currentData = currentData;
	}

	public void setComicChanged(IOnComicChanged comicChanged) {
		this.comicChanged = comicChanged;
	}

	public int getCurrentViewIndex() {
		return currentViewIndex;
	}

	public void setCurrentViewIndex(int currentViewIndex) {
		this.currentViewIndex = currentViewIndex;
	}

	public OnClickListener getOnClickImageViewSingerTapListener() {
		return onClickImageViewSingerTapListener;
	}

	public void setOnClickImageViewSingerTapListener(OnClickListener onClickImageViewSingerTapListener) {
		this.onClickImageViewSingerTapListener = onClickImageViewSingerTapListener;
	}
}
